<?php 
ini_set('date.timezone','Asia/Shanghai');
//error_reporting(E_ERROR);
require_once "../lib/WxPay.Api.php";
require_once "WxPay.JsApiPay.php";
require_once 'log.php';

//初始化日志
$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
$log =  Log::Init($logHandler, 15);

//①、获取用户openid
$tools = new JsApiPay();
/*数据整集*/
$rest = json_decode($_GET['rest'],true);
$openId = $tools->GetOpenid();
$orderId = uniqid();
$money = $rest['money']*100;
$sid = $rest['shopid'];
$sname = $rest['shopname'];
$swxcode = $rest['shopwx'];

//②、统一下单
$input = new WxPayUnifiedOrder();

$input->SetBody($sname);
$input->SetAttach($orderId);
$input->SetOut_trade_no(WxPayConfig::MCHID.date("YmdHis"));
$input->SetTotal_fee($money);
$input->SetTime_start(date("YmdHis"));
$input->SetTime_expire(date("YmdHis", time() + 600));
$input->SetGoods_tag($sid);
$input->SetOpenid($openId);
$input->SetNotify_url("http://www.linked-work.com/wxpay/example/notify.php");
$input->SetTrade_type("JSAPI");
$input->SetProduct_id($swxcode);

$order = WxPayApi::unifiedOrder($input);

$jsApiParameters = $tools->GetJsApiParameters($order);



//③、在支持成功回调通知中处理成功之后的事宜，见 notify.php
/**
 * 注意：
 * 1、当你的回调地址不可访问的时候，回调通知会失败，可以通过查询订单来确认支付是否成功
 * 2、jsapi支付时需要填入用户openid，WxPay.JsApiPay.php中有获取openid流程 （文档可以参考微信公众平台“网页授权接口”，
 * 参考http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html）
 */
?>

<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/> 
    <title>微信支付样例-支付</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script type="text/javascript">
	//调用微信JS api 支付
	function jsApiCall(){
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest',
			<?php echo $jsApiParameters; ?>,
			function(res){
				WeixinJSBridge.log(res.err_msg);
				if(res.err_msg == 'get_brand_wcpay_request:cancel'){
					alert('交易终止,请重新支付');
					/*交易取消,删除原待定订单*/
					var url = "http://www.linked-work.com/Interesting/index.php/Trade/removeTrade";
					$.post(url,{orderId:'<?php echo $orderId; ?>'},function (data){
						window.location.href="http://www.linked-work.com/Interesting/index.php?unid=<?php echo $sid; ?>";
					});
				}
//				alert(res.err_code+'\n'+res.err_desc+'\n'+res.err_msg);
				if(res.err_msg == 'get_brand_wcpay_request:ok'){
//					alert('交易完成');
					WeixinJSBridge.call('closeWindow');
				}
			}
		);
	}

	function callpay(){
		var trade_url = "http://www.linked-work.com/Interesting/index.php/Trade/createTrade";

		if (typeof WeixinJSBridge == "undefined"){
			/*微信订单生成本地待定订单*/
			$.ajax({
                cache: true,
                type: "POST",
                url:trade_url,
                data:$('#Frm').serialize(),
                async: true,
                error: function(request) {
                    alert("Connection error");
                },
                success: function(data) {
                    
                }
            });
			if( document.addEventListener ){
		        document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
		    }else if (document.attachEvent){
		        document.attachEvent('WeixinJSBridgeReady', jsApiCall); 
		        document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
		    };
		}else{
			/*微信订单生成本地待定订单*/
			$.ajax({
                cache: true,
                type: "POST",
                url:trade_url,
                data:$('#Frm').serialize(),// 你的formid
                async: true,
                error: function(request) {
                    alert("Connection error");
                },
                success: function(data) {
                    
                }
            });
            jsApiCall();
		}
	}
	</script>

</head>
<body onload="callpay()">
	<form hidden id="Frm">
		<input name="orderId" value="<?php echo $orderId; ?>"/>
		<input name="openId" value="<?php echo $openId; ?>"/>
		<input name="sunid" value="<?php echo $sid; ?>"/>
		<input name="sname" value="<?php echo $sname; ?>"/>
		<input name="scode" value="<?php echo $swxcode; ?>"/>
		<input name="trade" value="<?php echo $money; ?>"/>
	</form>
</body>
</html>